/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx.mybatis.interceptor;

import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.sql.Connection;
import java.util.Map;
import java.util.Properties;

/**
 * <p>Project: mybatis2021 - MyPager
 * <p>Powered by webrx On 2021-07-15 09:34:32
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 15
 */
////args: 你需要mybatis传入什么参数给你 type :你需要拦截的对象  method=要拦截的方法
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class MyPager implements Interceptor {
    public static void startPage(int c,int p){
        currpage = c;
        pagesize = p;
    }

    public static void startPage(int c){
        currpage = c;
    }

    public static int currpage = 1;
    public static int pagesize = 10;
    public static int recordcount = 0;
    public static int pagecount = 1;

    /**
     * 插件的核心处理方法
     *
     * @param invocation
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //System.out.println("拦截器:intercept(Invocation invocation)");
        var sh = invocation.getTarget();
        var mh = SystemMetaObject.forObject(sh);
        var ms = (MappedStatement) mh.getValue("delegate.mappedStatement");
        String msid = ms.getId();
        if (msid.endsWith("ByPage")) {
            //var ph = (ParameterHandler) mh.getValue("delegate.parameterHandler");
            //var param = (Map<String, Object>) ph.getParameterObject();
            String sql = mh.getValue("delegate.boundSql.sql").toString().trim() + String.format(" limit %d,%d", currpage * pagesize - pagesize, pagesize);
            mh.setValue("delegate.boundSql.sql", sql);
        }

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        //System.out.println("拦截器：plugin(Object target)");
        //固定的写法，第二个参数表示要代理的对象 this
        return Plugin.wrap(target, this);
    }

    /**
     * 要传给这个插件的配置信息
     *
     * @param p
     */
    @Override
    public void setProperties(Properties p) {
        //System.out.println("拦截器：setProperties(Properties p)");
        this.pagesize = Integer.parseInt(p.getOrDefault("pagesize", 15).toString());
        this.currpage = Integer.parseInt(p.getOrDefault("currpage", 1).toString());
        //System.out.println(this.pagesize);
    }
}
